package com.beanconvert.config;

import java.io.IOException;

import javax.xml.bind.JAXBException;

import com.beanconvert.common.Convention;
import com.beanconvert.xml.XmlTool;
import com.beanconvert.xml.bean.BeanConfig;
import com.beanconvert.xml.bean.BeanInfo;

public class ConfigTool {

	private static BeanInfo initBeanInfo(String beanInfoFile) {

		BeanInfo bi = null;

		try {
			bi = XmlTool.Xml2BeanInfo(beanInfoFile);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return bi;
	}

	public static int configure() {

		BeanConfig bc = null;
		try {
			bc = XmlTool.Xml2BeanConfig(Convention.CONFIG_FILE);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}

		if (bc == null) {
			System.out.println("===> Config is null.");
			return -3;
		}

		for (String strFileName : bc.getConvertConfig()) {

			BeanInfo bi = initBeanInfo(strFileName);

			Convention.BEAN_CONVERT_MODEL.add(bi);

		}

		return 0;

	}

	public static int configure(String configFile) {

		String strConfigFile = "";
		BeanConfig bc = null;
		
		if ((configFile == null)||(configFile.equals(""))){
			
			strConfigFile = Convention.CONFIG_FILE;
		}else 
			strConfigFile = configFile;
		
		try {
			bc = XmlTool.Xml2BeanConfig(strConfigFile);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}

		if (bc == null) {
			System.out.println("===> Config is null.");
			return -3;
		}

		for (String strFileName : bc.getConvertConfig()) {

			BeanInfo bi = initBeanInfo(strFileName);

			Convention.BEAN_CONVERT_MODEL.add(bi);

		}

		return 0;

	}
}
